
#include "midea_collection_view_single.h"

#if midea_collection_view_show

#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include "../base_scroll_ui/midea_flex.h"
#include "midea_collection_dynamic.h"
#include "../base_scroll_ui/midea_base_scroll_tool.h"
#include "../base_scroll_ui/midea_base_scroll_cell.h"


static void midea_collection_view_single_constructor(const lv_obj_class_t *class_p, lv_obj_t *obj);
static void midea_collection_view_single_destructor(const lv_obj_class_t *class_p, lv_obj_t *obj);
// 刷新所有UI item
void update_midea_collection_single_all_item(midea_collection_view_single *collection);

// list_view类
const lv_obj_class_t midea_collection_view_single_class = {
    .constructor_cb = midea_collection_view_single_constructor,
    .destructor_cb = midea_collection_view_single_destructor,
    .width_def = LV_PCT(100),
    .height_def = LV_PCT(100),
    .base_class = &lv_obj_class,
    .instance_size = sizeof(midea_collection_view_single)};


lv_obj_t *create_midea_collection_single(const char *collection_name,
                                  lv_obj_t *parent_view,
                                  lv_dir_t direction,
                                  void (*update_collection)(void *data, lv_obj_t *item_view, int32_t index, uint8_t ui_type),
                                  void (*install_collection)(void *data, lv_obj_t *item_view, int32_t index, uint8_t ui_type),
                                  void (*free_data)(void *data))
{
    lv_obj_t *content_view = lv_obj_class_create_obj(&midea_collection_view_single_class, parent_view);
    lv_obj_class_init_obj(content_view);

    lv_obj_center(content_view);

    midea_flex_init();

    midea_collection_view_single *new_collection = (midea_collection_view_single *)content_view;
    new_collection->collection_head = NULL;
    new_collection->collection_tail = NULL;
    new_collection->update_collection = update_collection;
    new_collection->install_collection = install_collection;
    new_collection->free_data = free_data;
    new_collection->create_item = NULL;
    new_collection->direction = direction;

    // 动态加载设置
    new_collection->dynamic_load_tag.load_tag = MIDEA_DYNAMIC_LOAD_AND_FREE;
    new_collection->dynamic_load_tag.init_load_count = MIDEA_COLLECTON_LOAD_ITEM_COUNT;
    new_collection->dynamic_load_tag.min_load_count = MIDEA_COLLECTON_LAZY_MIN_ITEM_COUNT;

    new_collection->count = 0;
    if (direction & LV_DIR_VER)
    {
        midea_obj_set_flex_flow(content_view, MD_FLEX_FLOW_ROW_WRAP);
    }
    else
    {
        midea_obj_set_flex_flow(content_view, MD_FLEX_FLOW_COLUMN_WRAP_PAGE_ROW);
    }

    lv_obj_set_style_pad_row(content_view, DEFAULT_COLLECTION_GAP, 0);
    lv_obj_set_style_pad_column(content_view, DEFAULT_COLLECTION_GAP, 0);

    lv_obj_set_scroll_dir(content_view, direction);
    return content_view;
}

static void midea_collection_view_single_constructor(const lv_obj_class_t *class_p, lv_obj_t *obj)
{
    LV_UNUSED(class_p);
    // 检测滑动相关事件
    // 触发懒加载逻辑

    lv_obj_add_event_cb(obj, midea_collection_scroll_event, LV_EVENT_ALL, NULL);
}
//@brief 释放
static void midea_collection_view_single_destructor(const lv_obj_class_t *class_p, lv_obj_t *obj)
{
    LV_UNUSED(class_p);
    midea_collection_view_single *collection = (midea_collection_view_single *)obj;
    free_midea_collection_single(collection);
}

// 删除collection_name下的数据源collection和collection本身
void free_midea_collection_single(midea_collection_view_single *collection)
{
    // 删除collection_name对应数据源下的所有数据（datasource_collection 下的 datasource_collection_data 和 用户数据）
    remove_midea_all_collection_single_data(collection);
    // 更新UI，没了数据，就是删除UI
    if (collection != NULL)
    {
        update_midea_collection_single_all_item(collection);
    }
}


// 末尾增加
void add_midea_collection_single_data(midea_collection_view_single *collection, void *data, uint8_t ui_type)
{
    if (collection == NULL)
    {
        return;
    }

    midea_collection_view_single_data *new_node = (midea_collection_view_single_data *)lv_mem_alloc(sizeof(midea_collection_view_single_data));
    new_node->data = data;
    new_node->ui_type = ui_type;
    new_node->next = NULL;
    new_node->prev = NULL;
    if (collection->collection_head == NULL)
    {
        collection->collection_head = new_node;
    }
    else if (collection->collection_tail == NULL)
    {
        new_node->prev = collection->collection_head;
        collection->collection_head->next = new_node;
        collection->collection_tail = new_node;
    }
    else
    {
        midea_collection_view_single_data *tail = collection->collection_tail;
        tail->next = new_node;
        new_node->prev = tail;
        collection->collection_tail = new_node;
    }
    collection->count += 1;
}


// 按索引增加
void add_midea_collection_single_data_with_index(midea_collection_view_single *collection, void *data, int32_t index, uint8_t ui_type)
{
    if (collection == NULL)
    {
        return;
    }

    if (index == 0)
    {
        // 添加到第一个
        midea_collection_view_single_data *new_node = (midea_collection_view_single_data *)lv_mem_alloc(sizeof(midea_collection_view_single_data));
        new_node->data = data;
        new_node->ui_type = ui_type;
        new_node->next = NULL;
        new_node->prev = NULL;

        midea_collection_view_single_data *old_head = collection->collection_head;
        if (old_head != NULL)
        {
            old_head->prev = new_node;
        }
        new_node->next = old_head;
        collection->collection_head = new_node;
        if (collection->collection_tail == NULL)
        {
            collection->collection_tail = old_head;
        }
        collection->count += 1;
        return;
    }
    else if (index == collection->count)
    {
        // 添加到最后一个
        add_midea_collection_single_data(collection, data, ui_type);
        return;
    }

    // index不是第一个也不是最后一个
    // 说明(index > 0 && index < collection->count)
    // 如果index > collection->count 则无法添加成功
    if (index > collection->count)
    {
        return;
    }
    int32_t current_index = 0;
    midea_collection_view_single_data *current = collection->collection_head;
    while (current != NULL)
    {
        if (current_index == index)
        {
            midea_collection_view_single_data *prev = current->prev;
            midea_collection_view_single_data *new_node = (midea_collection_view_single_data *)lv_mem_alloc(sizeof(midea_collection_view_single_data));
            new_node->data = data;
            new_node->ui_type = ui_type;
            new_node->next = NULL;
            new_node->prev = NULL;

            new_node->next = current;
            current->prev = new_node;

            prev->next = new_node;
            new_node->prev = prev;

            collection->count += 1;
            return;
        }
        current_index += 1;
        current = current->next;
    }
}

// 按索引删除
void remove_midea_collection_single_data(midea_collection_view_single *collection, int32_t index)
{
    if (collection == NULL || collection->collection_head == NULL)
    {
        return;
    }
    int32_t current_index = 0;
    midea_collection_view_single_data *current = collection->collection_head;
    while (current != NULL)
    {
        if (current_index == index)
        {
            midea_collection_view_single_data *prev = current->prev;
            midea_collection_view_single_data *next = current->next;
            // 删除节点的四种情况
            if (prev != NULL && next != NULL)
            {
                // 删除中间
                prev->next = next;
                next->prev = prev;
            }
            else if (prev == NULL && next != NULL)
            {
                // 删除第一个
                next->prev = NULL;
                collection->collection_head = next;
                if (collection->collection_head == collection->collection_tail)
                {
                    collection->collection_tail = NULL;
                }
            }
            else if (prev != NULL && next == NULL)
            {
                // 删除最后一个
                prev->next = NULL;
                if (prev != collection->collection_head)
                {
                    collection->collection_tail = prev;
                }
                else
                {
                    collection->collection_tail = NULL;
                }
            }
            else
            {
                // 删除完
                collection->collection_head = NULL;
                collection->collection_tail = NULL;
            }
            collection->free_data(current->data);
            lv_mem_free(current);
            collection->count -= 1;
            return;
        }
        current_index += 1;
        current = current->next;
    }
}

// 删除所有数据
void remove_midea_all_collection_single_data(midea_collection_view_single *collection)
{
    if (collection == NULL || collection->collection_head == NULL)
    {
        return;
    }

    int32_t current_index = 0;
    // 从前往后依次删除
    midea_collection_view_single_data *current = collection->collection_head;
    while (current != NULL)
    {
        midea_collection_view_single_data *temp = current;
        current = current->next;
        if (temp->data != NULL)
        {
            collection->free_data(temp->data);
        }
        temp->prev = NULL;
        temp->next = NULL;
        lv_mem_free(temp);
        current_index += 1;
    }
    collection->collection_head = NULL;
    collection->collection_tail = NULL;
    collection->count = 0;
}

// 按索引修改
void reset_midea_collection_single_data_with_index(midea_collection_view_single *collection, int32_t index, const void *new_data, uint8_t ui_type)
{
    if (collection == NULL || collection->collection_head == NULL)
    {
        return;
    }
    int32_t current_index = 0;
    midea_collection_view_single_data *current = collection->collection_head;
    while (current != NULL)
    {
        if (current_index == index)
        {
            if (new_data != NULL)
            {
                if (current->data != NULL)
                {
                    // 释放原来的data
                    collection->free_data(current->data);
                }
                current->data = new_data;
            }
            if (NOT_SET_COLLECTION_UI_TYPE != ui_type)
            {
                current->ui_type = ui_type;
            }
            return;
        }
        current_index += 1;
        current = current->next;
    }
}

// 对比数据并修改数据
// 调用者提供对比方法
// new_data为空则不修改
void reset_midea_collection_single_data_with_data(midea_collection_view_single *collection, const void *check_data, const void *new_data, uint8_t ui_type)
{
    if (collection == NULL || collection->collection_head == NULL || check_data == NULL)
    {
        return;
    }
    if (collection->is_same_data_func == NULL)
    {
        return;
    }
    // int32_t current_index = 0;
    midea_collection_view_single_data *current = collection->collection_head;
    while (current != NULL)
    {
        if (collection->is_same_data_func(current->data, check_data))
        {
            if (new_data != NULL)
            {
                // 释放原来的data
                if (current->data != NULL)
                {
                    collection->free_data(current->data);
                }
                current->data = new_data;
            }
            if (NOT_SET_COLLECTION_UI_TYPE != ui_type)
            {
                current->ui_type = ui_type;
            }

            return;
        }
        // current_index += 1;
        current = current->next;
    }
}

// 根据ui_type查找cell_ui
// from ui index
// 返回 cell
lv_obj_t *search_midea_collection_single_item_ui(midea_collection_view_single *collection, int32_t index, midea_collection_view_single_data *data)
{
    lv_obj_t *obj = (lv_obj_t *)collection;
    if (collection == NULL)
    {
        return;
    }
    for (int32_t i = index + 1; i < lv_obj_get_child_cnt(obj); i++)
    {
        lv_obj_t *next_item = lv_obj_get_child(obj, i);
        if (next_item != NULL && midea_base_scroll_cell_is_same_ui_type(next_item, data->ui_type))
        {
            return next_item;
        }
    }
    // 没找到
    return NULL;
}

// 交换cell_ui位置
void exchange_midea_collection_single_item_ui(midea_collection_view_single *collection, lv_obj_t *cell1, lv_obj_t *cell2)
{
    lv_obj_swap(cell1, cell2);
}

// 如果cell ui_type不一致则更新cell
void reinstall_midea_collection_single_item_ui(midea_collection_view_single *collection, lv_obj_t *cell, int32_t index, midea_collection_view_single_data *data)
{
    if (collection == NULL)
    {
        return;
    }
    if (midea_base_scroll_cell_is_same_ui_type(cell, data->ui_type))
    {
        // ui类型一致不需要更新
        return;
    }
    // 更新UI
    midea_base_scroll_cell_set_ui_type(cell, data->ui_type);
    // 删除cell的所有子元素
    lv_obj_clean(cell);
    // 初始化cell的子元素
    collection->install_collection(data->data, cell, index, data->ui_type);
}

// 在ui index处增加cell
lv_obj_t *add_midea_collection_single_item_ui(midea_collection_view_single *collection, int32_t index, midea_collection_view_single_data *data, bool set_ui_type)
{
    lv_obj_t *obj = (lv_obj_t *)collection;
    uint32_t old_count = lv_obj_get_child_cnt(obj);
    if (index < 0 || index > old_count)
    {
        return NULL;
    }
    lv_obj_t *add_cell;
    if (collection->create_item != NULL)
    {
        add_cell = collection->create_item(data->data, obj, index, data->ui_type);
        // cell必须继承 midea_base_scroll_cell_class
        if (!lv_obj_has_class(add_cell, &midea_base_scroll_cell_class))
        {
            lv_obj_del(add_cell);
            return NULL;
        }
    }
    else
    {
        add_cell = midea_base_scroll_cell_create(obj);
        lv_obj_set_style_bg_color(add_cell, lv_color_hex(0xffffff), LV_PART_MAIN);
        //lv_obj_set_style_bg_opa(add_cell, LV_OPA_100, 0);
    }
    if (set_ui_type)
    {
        midea_base_scroll_cell_set_ui_type(add_cell, data->ui_type);
    }

    if (old_count == index)
    {
        // 此时不需要更新ui index
        return add_cell;
    }
    // 更新ui index
    lv_obj_t *swap_cell = lv_obj_get_child(obj, index);
    if (swap_cell != NULL)
    {
        lv_obj_swap(swap_cell, add_cell);
    }
    return add_cell;
}

// 刷新所有UI item
void update_midea_collection_single_all_item(midea_collection_view_single *collection)
{
    lv_obj_t *obj = (lv_obj_t *)collection;
    int32_t index = 0;
    midea_collection_view_single_data *current = collection->collection_head;
    printf("current=%x\n",current);
    
    while (current != NULL)
    {
        lv_obj_t *cell = lv_obj_get_child(obj, index);
        printf("cell=%x\n",cell);
        if (cell == NULL)
        {
            // 增加
            // 这里add_cell的索引必然==index
            lv_obj_t *add_cell = add_midea_collection_single_item_ui(collection, index, current, true);
            if (add_cell != NULL)
            {
                collection->install_collection(current->data, add_cell, index, current->ui_type);
                cell = add_cell;
            }
        }
        else
        {
            // 比较ui_type是否一致
            if (!midea_base_scroll_cell_is_same_ui_type(cell, current->ui_type))
            {
                // 不一致则查找
                lv_obj_t *search_cell = search_midea_collection_single_item_ui(collection, index, current);
                if (search_cell != NULL)
                {
                    // 交换
                    exchange_midea_collection_single_item_ui(collection, cell, search_cell);
                    cell = search_cell;
                }
                else
                {
                    // 查找不到则 增加 或 更新
                    if (lv_obj_get_child_cnt(obj) < collection->count)
                    {
                        // 现有cell不足则增加
                        cell = add_midea_collection_single_item_ui(collection, index, current, false);
                    }
                    // 更新cell child使ui_type一致
                    reinstall_midea_collection_single_item_ui(collection, cell, index, current);
                }
            }
        }
        // 刷新
        collection->update_collection(current->data, cell, index, current->ui_type);

        index += 1;
        current = current->next;
    }
    // 如果还有其他的cell存在则删除
    midea_delete_child_from_index(obj, index, true);
}

// 刷新列表（默认情况刷新整个列表）
// 启用懒加载后默认当UI item数量为0时加载一定数量item
// 后续就不需要调用update_midea_collection_single方法
// 滑动列表时会自动刷新
void update_midea_collection_single(midea_collection_view_single *collection)
{
    if (collection == NULL)
    {
        return;
    }
    if (collection->dynamic_load_tag.load_tag & MIDEA_DYNAMIC_NONE)
    {
        update_midea_collection_single_all_item(collection);
        return;
    }
    lv_obj_t *obj = (lv_obj_t *)collection;
    uint32_t item_cout = lv_obj_get_child_cnt(obj);
    // 启用懒加载
    if (item_cout == 0)
    {
        // 初次
        midea_collection_dynamic_update(collection, MIDEA_COLLECTON_LOAD_ITEM_COUNT);
    }
    else
    {
        // 若未已经到达最大加载个则继续加载
        if (item_cout < MIDEA_COLLECTON_LOAD_ITEM_COUNT)
        {
            update_midea_collection_with_range(collection, 0, MIDEA_COLLECTON_LOAD_ITEM_COUNT - 1);
        }
        else
        {
            update_midea_collection_with_range(collection, 0, item_cout - 1);
        }
    }
}

// 按索引刷新
void update_midea_collection_single_with_index(midea_collection_view_single *collection, int32_t index)
{
    if (index < 0 || collection == NULL)
    {
        return;
    }
    lv_obj_t *obj = (lv_obj_t *)collection;
    // 如果collection->collection_head 链表中不包含索引 index
    // 则查找并删除视图上的对应UI item
    if (index >= collection->count)
    {
        lv_obj_t *del_item = lv_obj_get_child(obj, index);
        if (del_item != NULL)
        {
            lv_obj_del(del_item);
        }
        return;
    }

    int32_t current_index = 0;
    midea_collection_view_single_data *current = collection->collection_head;
    while (current != NULL)
    {
        if (index == current_index)
        {
            lv_obj_t *cell = lv_obj_get_child(obj, current_index);
            if (cell == NULL)
            {
                // 增加cell
                lv_obj_t *add_cell = add_midea_collection_single_item_ui(collection, current_index, current, true);
                if (add_cell != NULL)
                {
                    collection->install_collection(current->data, add_cell, current_index, current->ui_type);
                    cell = add_cell;
                }
            }
            else if (!midea_base_scroll_cell_is_same_ui_type(cell, current->ui_type))
            {
                // 更新cell child使ui_type一致
                reinstall_midea_collection_single_item_ui(collection, cell, index, current);
            }
            // 刷新cell
            if (cell != NULL)
            {
                collection->update_collection(current->data, cell, current_index, current->ui_type);
            }
            break;
        }

        current_index += 1;
        current = current->next;
    }
}

// 根据索引获取数据
void *midea_collection_single_get_data_with_index(midea_collection_view_single *collection, int32_t index)
{
    if (collection == NULL || collection->collection_head == NULL)
    {
        return NULL;
    }

    int32_t current_index = 0;
    midea_collection_view_single_data *current = collection->collection_head;
    while (current != NULL)
    {
        if (current_index == index)
        {
            return current->data;
        }
        current_index += 1;
        current = current->next;
    }
    return NULL;
}

// 根据数据获取索引 不存在返回-1
int32_t midea_collection_single_get_index_with_data(midea_collection_view_single *collection, void *data)
{
    if (collection == NULL || collection->collection_head == NULL)
    {
        return -1;
    }
    if (collection->is_same_data_func == NULL)
    {
        return -1;
    }
    int32_t current_index = 0;
    midea_collection_view_single_data *current = collection->collection_head;
    while (current != NULL)
    {
        if (collection->is_same_data_func(current->data, data))
        {
            return current_index;
        }
        current_index += 1;
        current = current->next;
    }
    return -1;
}

// 添加用户数据对比方法
void midea_collection_single_set_data_check_func(midea_collection_view_single *collection, bool (*is_same_data_func)(const void *par1, const void *par2))
{
    if (collection == NULL)
    {
        return;
    }
    collection->is_same_data_func = is_same_data_func;
}

// 添加用户collection item 创建方法
void midea_collection_single_set_item_create_func(midea_collection_view_single *collection, lv_obj_t *(*create_item)(void *data, lv_obj_t *parent, int32_t index, uint8_t ui_type))
{
    if (collection == NULL)
    {
        return;
    }
    collection->create_item = create_item;
}

// 修改懒加载设置
void midea_collection_single_set_dynamic_load_tag(midea_collection_view_single *collection, midea_dynamic_load_t load_tag)
{
    if (collection == NULL)
    {
        return;
    }
    collection->dynamic_load_tag = load_tag;
}
//@brief 修改每个cell之间的间距
//@param gap_hor 水平间距
//@param gap_ver 垂直间距
void midea_collection_single_set_gap(midea_collection_view_single *midea_collection_view_single, lv_coord_t gap_hor, lv_coord_t gap_ver)
{
    lv_obj_t *collection = (lv_obj_t *)midea_collection_view_single;
    if (collection == NULL)
    {
        return;
    }
    lv_obj_set_style_pad_row(collection, gap_hor, 0);
    lv_obj_set_style_pad_column(collection, gap_ver, 0);
}

//获取data数量
uint16_t midea_collection_single_get_data_count(midea_collection_view_single *collection)
{
    if (collection == NULL)
    {
        return 0;
    }
    return collection->count;
}



// 根据索引滚动到索引位置
void scroll_collection_view_single_to_index(midea_collection_view_single *collection, int32_t index)
{
    // collection 为NULL 直接返回
    if (collection == NULL || collection->collection_head == NULL)
    {
        return;
    }

    // 判断index是否合法
    int32_t total_count = collection->count;
    if (index < 0 || index > total_count)
    {
        return NULL;
    }

    lv_obj_t *obj = (lv_obj_t *)collection;
    uint32_t item_count = lv_obj_get_child_cnt(obj);

    // 如果index 超出当前加载的卡片数，加载更多的卡片数，默认再加10个卡片（大于一页显示的卡片数）
    if(index > item_count)
    {
        update_midea_collection_with_range(collection, 0, index + 10);
    }

    // 滚动到对应index的位置
    lv_obj_t *cell = lv_obj_get_child(obj, index);

    lv_coord_t gap = lv_obj_get_style_pad_row(obj, 0);

    lv_coord_t pos_y = lv_obj_get_y(cell);

    lv_obj_scroll_to_y(obj, pos_y + gap, LV_ANIM_ON);

    update_midea_collection_with_range(collection, 0, index + 10);
}

// 根据数据滚动到数据的位置
void scroll_collection_view_single_to_data(midea_collection_view_single *collection, void *data)
{
    // collection 为NULL 直接返回
    if (collection == NULL || collection->collection_head == NULL)
    {
        return;
    }
    int32_t index = midea_collection_single_get_index_with_data(collection, data);
    if(index == -1)
    {
        return;
    }
    scroll_collection_view_single_to_index(collection, index);
}



#endif